import classNames from 'classnames';
import * as echarts from 'echarts';
import { CSSProperties, useEffect, useRef } from 'react';

import classes from './index.module.scss';
const Chart: React.FC<{ option?: any; className?: string; style?: CSSProperties }> = ({ option, className, style }) => {
  const echart = useRef<echarts.ECharts>();
  const divRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (divRef.current && !echart.current) {
      echart.current = echarts.init(divRef.current);
    }
    if (echart.current) {
      try {
        echart.current.setOption(option);
      } catch (error) {
        console.error(error);
      }
    }
  }, [option]);
  useEffect(() => {
    const observer = new ResizeObserver(() => {
      if (echart.current) {
        echart.current.resize();
      }
    });
    if (divRef.current) {
      observer.observe(divRef.current);
    }
    return () => {
      if (echart.current) {
        echart.current.dispose();
      }
      observer.disconnect();
    };
  }, []);
  return <div ref={divRef} style={style} className={classNames(classes.wrap, className)}></div>;
};

export default Chart;
